'use strict'
let  resultmodel=require('../model/index');
/*查询*/
let fn_list = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || '';
    if (keyword) {
        let list;
        list = await resultmodel.Blog.findAll({
            where: {
                [resultmodel.Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { Title: keyword },
                    { Abstract: keyword},
                    { Content: keyword },
                    { Classification: keyword},
                    { Author: keyword },
                ]
            },
            order:['id']
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: 'aaa'
        }
    } else {
        let list = await resultmodel.Blog.findAll({
            order:['id']
        });
        ctx.body = {
            code: 1000,
            data: list,
            msg: 'bbb'
        }
    }
}
/*id*/
let fn_getbyid = async (ctx, next) => {
    let id = ctx.request.params.id;
    let blog = await resultmodel.Blog.findByPk(id);
    if (blog) {
        ctx.body = {
            code: 1000,
            data: blog,
            msg: 'aaa'
        }
    } else {
        ctx.body = {
            code: 900,
            data: '',
            msg: 'bbb'
        }
    }
}
/*增加*/
let fn_post =async (ctx, next) => {
    let obj = ctx.request.body;
    await resultmodel.Blog.create(obj);
    ctx.body = obj;
}
/*编辑*/
let fn_put =async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    let blog = await resultmodel.Blog.findByPk(id);
    if (blog) {
        resultmodel.Blog.update(obj,{
            where:{
                id:id
            }
        })
        ctx.body = {
            code: 1000,
            data: blog,
            msg: 'aaa'
        }
    } else {
        ctx.body = {
            code: 300,
            data: '',
            msg: 'bbb'
        }
    }
}
/*删除*/
let fn_delete =async (ctx, next) => {
    let id = ctx.request.params.id;
    let blog = await resultmodel.Blog.findByPk(id);
    if (blog) {
        resultmodel.Blog.destroy({
            where:{
                id:id
            }
        })
        ctx.body = {
            code: 1000,
            data: { id },
            msg: 'aaa'
        }
    } else {
        ctx.body = {
            code: 500,
            data: null,
            msg: 'bbb。'
        }
    }
}
module.exports={
    'get /blog':fn_list,
    'get /blog/:id':fn_getbyid,
    'post /blog':fn_post,
    'put /blog/:id':fn_put,
    'delete /blog/:id':fn_delete
}